
import os
from datetime import date, datetime
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets, QtGui

from .config import CONFIG_PATH, load_config_list, TimerConfig, make_config_json


__author__ = 'chb'


class Timer(QWidget):
    def __init__(
            self, 
            event_dtime: datetime, event_name: str, annual: bool,
            config: TimerConfig, as_label=False):
        super().__init__(None)
        self.setWindowFlags(Qt.FramelessWindowHint|Qt.WindowStaysOnBottomHint|Qt.SubWindow)
        self.setAutoFillBackground(False)
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.repaint()

        quit_action = QAction('退出', self, triggered=self.quit)
        self.tray_icon_menu = QMenu(self)
        self.tray_icon_menu.setIcon(QIcon('./shime1.jpg'))
        self.tray_icon_menu.addAction(quit_action)
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(QIcon('./shime1.jpg'))
        self.tray_icon.setContextMenu(self.tray_icon_menu)
        self.tray_icon.show()

        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self._show_menu)

        self.label = QLabel(self)
        self.label.setText('Hello world')
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setStyleSheet('color:white')

        font = QFont()
        font.setPointSize(50)
        font.setFamily('Microsoft YaHei')
        font.setBold(True)
        self.label.setFont(font)

        box = QVBoxLayout()
        box.addWidget(self.label)

        self.is_follow_mouse = False
        self.mouse_drag_pos = self.pos()
        self.resize(512, 128)
        self.setLayout(box)

        if not as_label:
            self.timer = QTimer()
            self.timer.timeout.connect(self.start_countdown)
            self.timer.start(10)

            self.timer2 = QTimer()
            self.timer2.timeout.connect(self.report_pos)
            self.timer2.start(500)
        else:
            self.show()
            return

        self._event_dtime = event_dtime
        self._event_name = event_name

        self._config = config

        if annual:
            while datetime.now() > self._event_dtime:
                etime = event_dtime
                self._event_dtime = datetime(
                    datetime.now().year + 1,
                    etime.month, etime.day, etime.hour, etime.second 
                )
        
        self.move(config.x, config.y)
        self.show()

    def _show_menu(self, p):
        dest_point=self.mapToGlobal(p)
        self.tray_icon_menu.exec_(dest_point)

    def report_pos(self):
        print(self.x(), self.y())
        self._config.x = self.x()
        self._config.y = self.y()
        self._config.set_xy_handler()

    def start_countdown(self):
        delta = self._event_dtime - datetime.now()
        self.label.setText(
            '距离%s仅剩\n%s' % (
                self._event_name, 
                str(delta)[:-4])
        )

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.is_follow_mouse = True
            self.mouse_drag_pos = event.globalPos() - self.pos()
            event.accept()
            self.setCursor(QCursor(Qt.OpenHandCursor))
            
    def mouseMoveEvent(self, event):
        if Qt.LeftButton and self.is_follow_mouse:
            self.move(event.globalPos() - self.mouse_drag_pos)
            event.accept()
            
    def mouseReleaseEvent(self, event):
        self.is_follow_mouse = False
        self.setCursor(QCursor(Qt.ArrowCursor))
        
    def quit(self):
        self.close()
        sys.exit()


class TimerLauncher:
    def __init__(self, cfg_path=CONFIG_PATH):
        self._timer_configs = []
        self._cfg_path = cfg_path
        self.__app = QApplication(sys.argv)
        
        self.load_config()
    
    def load_config(self):
        if not os.path.exists(self._cfg_path):
            return

        self._timer_configs = load_config_list(
            open(self._cfg_path).read(), self.save_config
        )
        print(self._timer_configs)

    def launch_all_timers(self):
        cfgs = self._timer_configs
        if not cfgs:
            print('no timer config')
            timer = Timer(None, None, None, None, True)
            timer.label.setText('<no timer>')
            self.__app.exec_()
            return

        for config in cfgs:
            timer = Timer(
                config.datetime, config.event, config.annual, config)
            timer.show()

        self.__app.exec_()

    def save_config(self):
        print('save config')
        with open(self._cfg_path, 'w') as f:
            source = make_config_json(self._timer_configs)
            f.write(source)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    _ = Timer()
    sys.exit(app.exec_())
